package com.kanshu.basictest.service;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import androidx.annotation.Nullable;
import android.util.Log;

import com.kanshu.basictest.constants.PubContants;

public class MessengerService extends Service implements Handler.Callback {

    public static final String TAG = "MessengerService";

    private final Handler mHandler = new Handler(this);

    private final Messenger server = new Messenger(mHandler);


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return server.getBinder();
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case PubContants.MSG_FROM_CLIENT:
                //处理来自于客户端的消息
                Log.i(TAG, "handleMessage: 接收到来自于客户端的消息：" + msg.getData().getString("msg"));
                //回应客户端
                Messenger client = msg.replyTo;
                if (client != null) {
                    Message replyMsg = Message.obtain(null, PubContants.MSG_FROM_SERVER);
                    Bundle bundle = new Bundle();
                    bundle.putString("reply", "这里是服务端，已接收到你的消息！");
                    replyMsg.setData(bundle);
                    try {
                        client.send(replyMsg);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
                break;
        }


        return true;
    }
}
